package nacos

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"sftti-go-service/pkg/db"
	"sftti-go-service/pkg/oss"
	"sftti-go-service/types"

	"github.com/dubbogo/gost/log/logger"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"gopkg.in/yaml.v2"
)

var (
	configClient     config_client.IConfigClient
	DbConfigValue    types.DatabaseConfig
	PropsConfigValue types.PropsConfig
	OssConfigValue   types.OssConfig
	DubboConfigValue types.DubboConfig
)

func init() {
	var err error

	var yamlContent []byte
	var folderPath string
	folderPath, _ = os.Getwd()

	logger.Infof("##folderPath=%s", folderPath)

	dubbogoPath := filepath.Join(folderPath, "../conf/dubbogo.yaml")
	yamlContent, err = os.ReadFile(dubbogoPath)

	if err != nil {
		logger.Errorf("###Read dubbogo.yaml Err")
		panic(err)
	}

	err = yaml.Unmarshal(yamlContent, &DubboConfigValue)

	if err != nil {
		logger.Errorf("###Parse dubbogo.yaml Err")
		panic(err)
	}

	tmpSpts := strings.Split(DubboConfigValue.DubboConfigCenterConfig.DubboConfigCenter.Address, ":")
	var port uint64
	port, _ = strconv.ParseUint(tmpSpts[1], 10, 64)
	sc := []constant.ServerConfig{{
		IpAddr: tmpSpts[0],
		Port:   port,
	}}

	cc := constant.ClientConfig{
		NamespaceId:         DubboConfigValue.DubboConfigCenterConfig.DubboConfigCenter.Namespace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "log",
		CacheDir:            "cache",
		LogLevel:            "error",
	}

	configClient, err = clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		logger.Errorf("###NacosClient Init Err:%s", err)
		panic(err)
	}

	err = getAllObjects()

	if err != nil {
		logger.Errorf("###Nacos Get Data Err:%s", err)
		panic(err)
	}

	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: DubboConfigValue.DubboConfigCenterConfig.DubboConfigCenter.DataId,
		Group:  DubboConfigValue.DubboConfigCenterConfig.DubboConfigCenter.Group,
		OnChange: func(namespace, group, dataId, data string) {

			logger.Infof("###Nacos Changed:%s", data)
			fillObject(data, &DbConfigValue)

			fillObject(data, &OssConfigValue)

			fillObject(data, &PropsConfigValue)

		},
	})

	if err != nil {
		logger.Errorf("###Nacos Listen Config Err:%s", err)
		os.Exit(-1)
	}

	//初始化数据库
	db.InitDb(DbConfigValue)
	//初始化OssClient
	oss.InitOss(OssConfigValue)
}

func fillObject(content string, obj interface{}) {
	err := yaml.Unmarshal([]byte(content), obj)
	if err != nil {
		fmt.Println(err)
	}
}

func getAllObjects() error {

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: DubboConfigValue.DubboConfigCenterConfig.DubboConfigCenter.DataId,
		Group:  DubboConfigValue.DubboConfigCenterConfig.DubboConfigCenter.Group,
	})

	if err != nil {
		return err
	}

	fillObject(content, &DbConfigValue)

	fillObject(content, &OssConfigValue)

	fillObject(content, &PropsConfigValue)

	return nil
}
